package com.zhn.evsi.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.AppendObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.zhn.evsi.common.enums.FileStates;
import com.zhn.evsi.config.OssConfig;
import com.zhn.evsi.domain.entity.System.SysFile;
import com.zhn.evsi.mapper.SysFileMapper;
import com.zhn.evsi.service.ISysFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * OSS文件上传
 */
@Component
public class OSSUtil {

    @Autowired
    private OssConfig ossConfig;

    @Resource
    private TimeUtil timeUtil;

    @Autowired
    private SysFileMapper fileMapper;

    /**
     * 上传图片到阿里云oss中
     */
    public String OSSUpload(MultipartFile file, String filePath, Integer state, String username) {

        // 将参数拿出来
        String endpoint = ossConfig.getEndpoint();
        String accessKeyID = ossConfig.getAccessKeyID();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();

        // 创建oss对象
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyID, accessKeySecret);

        // 文件输入流
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        // 获取文件名称与后缀
        String fileName = file.getOriginalFilename();
        String fileExtName = fileName.substring(fileName.lastIndexOf("."));

        // meta设置请求头
        // 是否可下载
        ObjectMetadata metadata = new ObjectMetadata();
        // state = 0 可下载
        if (state != 0) {
            if (state.equals(FileStates.FILE_IMAGE.getState())) {
                metadata.setContentType(FileStates.FILE_IMAGE.getStateInfo());
            }
        }

        // 设置存储路径
        String fileUrl = "evsi" + "/" + filePath + "/" + IdUtil.simpleUUID() + fileExtName;

        // 存储
        PutObjectRequest request = new AppendObjectRequest(bucketName, fileUrl, inputStream, metadata);
        PutObjectResult result = ossClient.putObject(request);
        ossClient.shutdown();

        // 将文件存入mysql中，（id，文件路径，文件类型，md5，上传时间，上传人）
        String url = "https://" + bucketName + "." + endpoint + "/" + fileUrl;

        fileMapper.insert(SysFile.builder()
                .filePath(url)
                .fileFunction(filePath)
                .fileType(file.getContentType())
                .fileMd5(result.getETag())
                .uploadTime(timeUtil.TimeFormatOnSecond())
                .uploadBy(username)
                .state(state)
                .build());
        return url;
    }


}
